<!-- 添加好友视图 -->
<template>
    <div id='addF_container'>
        <!-- 标题盒子 -->
        <div id="title_box">
            <!--返回按钮-->
            <div id="return_btn" @click="returnHandle">
                <img src="../public/return.png" alt="返回" srcset="">
            </div>
            <div id="title_text">{{ pageTitle }}</div>
        </div>
        <!-- 搜索框 -->
        <div id="searchBox">
            <el-input v-model="searchEmail" size="large" placeholder="请输入邮箱或群号" :suffix-icon="Search"
                @keyup.enter="searchHandler" />
        </div>
        <!-- 搜索结果 -> 用户 -->
        <div id="searchResult" v-show="resultBoxShow">
            <!-- 用户信息 -->
            <div id="user_picture"><img :src="userImage" alt="" srcset=""></div>
            <div id="user_info">
                <div id="user_name">{{ userInfo.name }}</div>
                <div style="height: 3px;"></div><!---占位-->
                <div>{{ userInfo.email }}</div>
            </div>
            <!-- 右侧添加按钮 -->
            <div id="addBtnBox">
                <el-button type="success" round @click="addHandle">添加</el-button>
            </div>
        </div>
        <!-- 搜索结果 - 群组 -->
        <div id="searchResultGroup" v-show="searchResultGroup">
            <div id="group_img"><img :src="groupinfo.img" alt="群组头像" srcset=""></div>
            <div id="group_info">
                <div id="group_name">{{ groupinfo.groupName }}</div>
                <div id="group_number">{{ groupinfo.groupNumber }}</div>
            </div>
            <!-- 右侧处理按钮 -->
            <div id="btns">
                <el-button type="success" plain @click="applyHandle">申请</el-button>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from "../public/axiosConfig"
import { getValueBykey, getLoginUserId } from "../src/indexDB/dbKV";

// 标题
let pageTitle = ref("添加好友/群组");
// 搜索邮箱/群号
let searchEmail = ref("");
// 搜索结果-用户信息
let userInfo = ref({})
// 搜索用户头像 - indexDB中随机取到
let userImage = ref("");
// 控制结果框显示和隐藏
let resultBoxShow = ref(false);
// 群组搜索结果框
let searchResultGroup = ref(false);
// 群组搜索列表
let groupinfo = ref([]);

onMounted(() => {
    resultBoxShow.value = false; // 页面初始化隐藏结果盒子
})

// 搜索执行处理器
function searchHandler() {
    // 鉴空操作
    if (searchEmail.value == "") {
        showMessage("info", "输入为空!");
        hideSearchBox();
        return 1;
    }

    // 检查输入邮箱是否合法
    if (!isValidEmail(searchEmail.value)) {
        // showMessage("error", "输入邮箱不合法!")
        // 不合法，作为群号搜索
        execSearchGroup();
        return 0;
    }

    // 执行搜索
    execSearch();
}

// 群组申请处理器
async function applyHandle(){
    // 获取当前登录用户ID
    let loginUserId = await getLoginUserId();
    // 构造请求参数对象，发送请求申请
    let paramObj = {groupId: groupinfo.value.groupId, userId: loginUserId, state: 0}
    const { data: res } = await axios.post("/groupUsers/applyIntoGroup", paramObj);
    if(res.code == 0){
        // console.log(res.msg);
        showMessage("error", res.msg);
        return 0;
    }
    
    showMessage("success", res.data);
}

// 搜索执行器 - 群组搜索
async function execSearchGroup() {
    const { data: res } = await axios.get(`/groupInfos/getGroupInfoByGroupNumber/${searchEmail.value}`)
    if (res.data == null) {
        showMessage("info", "无搜索结果")
        return 1;
    }

    // 有数据，控制群组盒子展示，隐藏用户盒子展示
    searchResultGroup.value = true; // 显示群组结果盒子
    resultBoxShow.value = false;
    // 动态添加头像字段
    res.data['img'] = await randamGetImg();
    groupinfo.value = res.data;
}

// 搜索执行器 - 用户搜索
async function execSearch() {
    const { data: res } = await axios.get(`/userInfos/getUserByEmail/${searchEmail.value}`);
    if (res.code == 0) {
        showMessage("info", "此用户不存在!");
        hideSearchBox();
        return 1;
    }

    // 将搜索到的用户消息展示赋值
    userImage.value = await randamGetImg(); // 取头像
    userInfo.value = res.data;
    resultBoxShow.value = true; // 显示搜索结果盒子
    searchResultGroup.value = false;
}

// 添加处理器 - 用户
async function addHandle() {
    // 判断用户是否为自己
    let loginUserInfo = await getValueBykey("userInfo");
    let loginUserId = loginUserInfo.userId;

    if (loginUserId == userInfo.value.userId) {
        showMessage("info", "无法添加自己!")
        return 1;
    }

    // 执行添加
    execAddhandle(loginUserId, userInfo.value.userId);
}

// 添加执行器 - 用户
async function execAddhandle(addId, beAddId) {
    let { data: res } = await axios.post(`/friendss/addFriend/${addId}/${beAddId}`);
    if (res.code == 0) {
        showMessage("error", res.msg);
        return 0;
    }

    showMessage("success", "用户添加成功！");
}

// 返回上一页
function returnHandle() {
    window.history.back();
}

// 判断邮箱格式的函数
function isValidEmail(email) {
    // 正则表达式，用于验证邮箱格式
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
}

// 通用消息提示函数
function showMessage(messageType, messageText) {
    ElMessage({
        message: messageText,
        type: messageType,
    })
}

// 隐藏搜索结果盒子
function hideSearchBox() {
    resultBoxShow.value = false;
}

// 随机获取一张头像 
async function randamGetImg() {
    let imgs = await getValueBykey("myPictures");
    let randomIndex = Math.floor(Math.random() * imgs.length);
    return imgs[randomIndex];
}

</script>

<style scoped>
#title_box {
    max-width: 700px;
    font-size: 16px;
    box-sizing: border-box;
    background-color: #d7e5ee;
    width: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    padding: 15px 20px;
    display: flex;
    justify-content: center;
    align-content: center;
}

#searchBox {
    /* height: 200px;
    border: solid red 1px; */
    margin-top: 60px;
}

#searchResult {
    margin-top: 13px;
    /* border: solid red 1px; */
    display: flex;
    flex-direction: row;
    box-shadow: 0px 0px 5px #cccaca;
    border-radius: 10px;
    padding: 5px 2px;
    position: relative;
}

#user_picture img {
    width: 45px;
    border-radius: 10px;
}

#user_name {
    font-size: 15px;
    font-weight: 600;
}

#user_info {
    font-size: 14px;
    margin-left: 7px;
}

#addBtnBox {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 10px;
    top: 13px;
}

#return_btn {
    position: absolute;
    left: 8px;
    top: 14px;
}

#return_btn img {
    width: 24px;
}

#group_img img {
    width: 46px;
    border-radius: 10px;
}

#group_info {
    margin-left: 7px;
}

#group_name {
    font-size: 15px;
}

#group_number {
    font-size: 13px;
    color: #474747;
    padding-top: 3px;
}

#searchResultGroup {
    display: flex;
    flex-direction: row;
    margin-top: 10px;
    position: relative;
    /* border: solid red 1px; */

}

#btns{
    /* border: solid red 1px; */
    position: absolute;
    right: 10px;
    top: 10px;
}
</style>